/**
 * @module 简易版本vue
 * @author xiongsha
 * @date 2021-04-18 20:50:05
 */
import React from 'react';
import Dep from './Dep';

class Avue {
  $options: any;

  $data: any;

  $dep: never[];

  constructor(options) {
    this.$options = options;
    this.$data = options.data;
    this.$dep = [];
    this.observe(this.$data);
  }

  observe(value) {
    if (!value || typeof value !== 'object') {
      return;
    }
    Object.keys(value).forEach((key) => {
      this.defineReactive(value, key, value[key]);
    });
  }

  defineReactive(obj, key, val) {
    this.observe(val);
    let dep = new Dep();
    Object.defineProperty(obj, key, {
      get() {
        if (dep.target) {
          dep.addWatcher(dep.target);
        }
        return val;
      },
      set(newVal) {
        if (val === newVal) return;
        val = newVal;
      },
    });
  }
}

export default Avue;
